﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace WinPhone.Models
{
    public class Repository
    {
           
        private const string SOMEE_CONN_STRING = @"workstation id=EJournalDB.mssql.somee.com;packet size=4096;user id=varela_SQLLogin_1;pwd=t3m3exaq6p;data source=EJournalDB.mssql.somee.com;persist security info=False;initial catalog=EJournalDB";
        private ChessDataDataContext _eJDataContext;
        public Repository()
        {
            string connStr = ConfigurationManager.ConnectionStrings["ChessConnectionString"].ConnectionString;
            
            _eJDataContext = new ChessDataDataContext(connStr);
        }

        private sealed class RepositoryCreator
        {
            private static readonly Repository instance = new Repository();
            public static Repository Instance { get { return instance; } }
        }

        public static Repository Instance
        {
            get { return RepositoryCreator.Instance; }
        }
        /// <summary>
        /// Добавление игрока
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public int addGemer(string login, string password)
        {
            var gamer = new GamerTable();

            gamer.login = login;
            gamer.password = password;


            _eJDataContext.GamerTable.InsertOnSubmit(gamer);
            _eJDataContext.SubmitChanges();

            return gamer.Id_gamer;
        }
        /// <summary>
        /// Есть ли игрок  в базе 
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public bool InLoginSubmit(string login)
        {
            var f = from n in _eJDataContext.GamerTable.ToList()
                    where n.login.Replace(" ","") == login
                    select n.Id_gamer;
            int count = f.Count();
            if (count == 1)
            {
               return true;
            }
            return false;


        }
     /// <summary>
        /// Добавление игры
     /// </summary>
     /// <param name="FirstGamer"> логин первого игрока</param>
     /// <param name="FirstGamerColor"> </param>
     /// <param name="GameStartTime"> </param>
     /// <param name="SecondGamer"></param>
     /// <returns></returns>
        public int addGame(string FirstGamer ,string FirstGamerColor,DateTime GameStartTime,string SecondGamer)
        {
            var Game = new GameTable();
            Game.firstGamerColor = FirstGamerColor;
            Game.firstGamerLogin = FirstGamer;
            Game.gameStartTime = GameStartTime;
            Game.secondGamerLogin = SecondGamer;


            _eJDataContext.GameTable.InsertOnSubmit(Game);
            _eJDataContext.SubmitChanges();

            return Game.Id_game;
        }
        /// <summary>
        /// Получить список игр по firstGamerLogin
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public List<GameTable> getAllGame(string login)
        {
            var f = from n in _eJDataContext.GameTable.ToList()
                    where n.firstGamerLogin.Replace(" ","") == login
                    select n;


            if (f.ToList().Count != 0)
            {
                foreach (GameTable gt in f)
                {
                    gt.firstGamerColor = gt.firstGamerColor.Replace(" ", "");
                    gt.firstGamerLogin = gt.firstGamerLogin.Replace(" ", "");
                    gt.secondGamerLogin = gt.secondGamerLogin.Replace(" ", "");
                }
                return f.ToList();


            }
            var second = from n in _eJDataContext.GameTable.ToList()
                    where n.secondGamerLogin.Replace(" ", "") == login
                    select n;
            foreach (GameTable gt in second)
            {
                gt.firstGamerColor = gt.firstGamerColor.Replace(" ", "");
                gt.firstGamerLogin = gt.firstGamerLogin.Replace(" ", "");
                gt.secondGamerLogin = gt.secondGamerLogin.Replace(" ", "");
            }
            return second.ToList();
        }

        public StrokeResult getLastStroke(string login, int gameId)
        {
            var f = from n in _eJDataContext.Stroke.ToList()
                    where n.GameId == gameId
                    select n;

            if (f.ToList().Count > 0)
            {
                int temp = f.ToList()[0].Id;
                int index = 0;
                foreach (Stroke s in f.ToList())
                {
                    if (s.Id > temp)
                    {
                        temp = s.Id;
                        index = f.ToList().IndexOf(s);
                    }
                }
                if (f.ToList()[index].LoginLastStep.Replace(" ","") != login)
                {
                    StrokeResult result = new StrokeResult();
                    result.StepFrom = f.ToList()[index].StepFrom.Replace(" ", "");
                    result.StepTo = f.ToList()[index].StepTo.Replace(" ", "");
                    result.isMate = false;
                    if (f.ToList()[index].StepTo.Replace(" ", "") == "f7")
                    {
                        result.isMate = true;
                    }
                    return result;
                }
                else
                    {
                        StrokeResult result = new StrokeResult();
                        result.isMate = false;
                        if (f.ToList()[index].StepTo.Replace(" ", "") == "f7")
                        {
                            result.isMate = true;
                        }
                        return result;
                    }
            }
            else
                return new StrokeResult();
        }

        public bool addStroke(int gameId, string login, string cellFrom, string cellTo)
        {
            try
            {
                var stroke = new Stroke();

                stroke.LoginLastStep = login;
                stroke.GameId = gameId;
                stroke.StepFrom = cellFrom;
                stroke.StepTo = cellTo;

                _eJDataContext.Stroke.InsertOnSubmit(stroke);
                _eJDataContext.SubmitChanges();

                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool deleteGame(int gameId, string login)
        {
            try
            {
                var f = from n in _eJDataContext.GameTable.ToList()
                        where n.Id_game == gameId
                        select n;
                _eJDataContext.GameTable.DeleteOnSubmit(f.First());
                _eJDataContext.SubmitChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public bool sendChallenge(string login, int gameId)
        {
            try
            {
                var f = from n in _eJDataContext.GameTable.ToList()
                        where n.Id_game == gameId
                        select n;
                f.First().secondGamerLogin = login;
                _eJDataContext.SubmitChanges();
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}